package com.disapand.dingdang.service

import cn.dev33.satoken.stp.StpUtil
import com.disapand.dingdang.common.ResponseEnum
import com.disapand.dingdang.dto.RoleDTO
import com.disapand.dingdang.exception.DDException
import com.disapand.dingdang.model.Role
import com.disapand.dingdang.model.roles
import org.ktorm.database.Database
import org.ktorm.dsl.eq
import org.ktorm.entity.add
import org.ktorm.entity.find
import org.ktorm.entity.update
import org.springframework.stereotype.Service
import java.time.LocalDateTime

/**
 * @author disapand
 * @date 2022/3/9 - 21:35 星期三
 */
@Service
class RoleService(private val database: Database) {

    /**
     * 添加或更新角色
     *
     * @param dto
     */
    fun save(dto: RoleDTO) {
        val role: Role?
        if (dto.id != null) {
            role = getById(dto.id)
            if (role != null) {
                when {
                    dto.role != null -> role.role = dto.role
                    dto.roleName != null -> role.roleName = dto.roleName
                }
                role.updatedAt = LocalDateTime.now()
                role.updatedBy = StpUtil.getLoginIdAsInt()
                database.roles.update(role)
            } else {
                throw DDException(ResponseEnum.DATA_NOT_FOUND, "未找到角色信息")
            }
        } else {
            role = Role {
                this.role = dto.role!!
                this.roleName = dto.roleName!!
            }
            database.roles.add(role)
        }
    }

    /**
     * 根据 id 获取角色详情
     *
     * @param id
     * @return
     */
    fun getById(id: Int): Role? {
        return database.roles.find { it.id eq id }
    }
}